python迭代器与生成器

迭代器

迭代器是一个实现了iter()和next()方法的对象

生成器

生成器的产生有两种方式:

yield函数(生成器函数)

生成器函数 Generator Function:实现迭代逻辑的函数

  • 任何包含yield语句的函数,都是生成器函数
  • 生成器函数是生成器的核心,用来实现迭代逻辑
  • 对于函数来说,yield和return功能接近,但不完全相同
1
2
3
4
5
6
7
8
9
10
11
12
13
def getValue():
import random
ls = list(range(10))
print(ls, end=",")
return ls[random.randint(0,9)]

for i in range(10):
print(getValue())

'''
普通函数 每次调用完局部变量都会销毁,如果表达容器概念,那么容器中的元素每次都需要重新生成,浪费了计算资源
有效提高CPU,内存的利用率,提高速度,优化必备
'''
1
2
3
4
5
6
7
8
9
def getValue( max ):
import random
ls = list(range(10))
print(ls, end=",")
for i in range( max ):
yield ls[random.randint(0,9)]

for i in getValue(10):
print(i)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def fibo_yield(max):
n,a,b = 0,0,1
while n < max:
yield b
a,b = b,a+b
n += 1

def read_file(fpath):
BLOCK_SIZE = 1024
with open(fpath,'rb') as f:
while True :
block = f.read(BLOCK_SIZE)
if block:
yield block
else:
return
```

```python
# send next close
def week(start):
n = start
day = {0:'星期日',1:'星期一',2:'星期二',3:'星期三',4:'星期四',5:'星期五',6:'星期六',}
while n <= 6:
msg = yield day[n]
print('msg:%s'%msg)
n +=1
n %= 7

day = week(3)
print(next(day))
print(day.send(None))
day.close()
print(day.send('Python大法好'))

'''
=============== RESTART: C:/Users/xiaoy/Desktop/yield_close.py ===============
星期三
msg:None
星期四
Traceback (most recent call last):
File "C:/Users/xiaoy/Desktop/yield_close.py", line 14, in <module>
print(day.send('Python大法好'))
StopIteration
'''

```

### 生成器表达式
~~~python
# 返回一个生成器
(do(i) for i in iter)
(do(i) for i in iter if condition)
(do(i,j) for i in iter for j in iter2)

生成器与迭代器的联系和区别

  1. 生成器Generator是快速实现迭代器类型的方式
  2. 生成器表达式和生成器函数都可以创建一个’generator’对象,这个对象是可迭代的(拥有__iter__()和__next__()方法),所以也叫迭代器。
  3. 生成器是迭代器的另一个角度诠释,生成器都是迭代器
  4. 生成器以逐一产生数据为角度,重点在于迭代逻辑的方便实现
  5. 生成器只需要yield保留字即可定义并表达,不用实现对象的iter和next方法